package com.zbl.zblproject.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Strings;
import com.zbl.zblproject.core.entity.*;
import com.zbl.zblproject.core.mapper.*;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.erp.entity.*;
import com.zbl.zblproject.erp.mapper.BalanceMapper;
import com.zbl.zblproject.erp.mapper.ErpCategoryMapper;
import com.zbl.zblproject.erp.mapper.ErpGoodMapper;
import com.zbl.zblproject.erp.service.ErpGoodService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/8
 * ERP GOOD 核心接口
 * 实现了产品 增删改查
 */
@Api(value = "ERP商品接口", tags = {"ERP商品接口"})
@RestController
@RequestMapping("/erp-goods")
public class ErpGoodsController {

    @Autowired
    private SmallUnitMapper smallUnitMapper;

    @Autowired
    private ErpGoodService erpGoodService;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ErpGoodMapper goodMapper;

    @Autowired
    private BalanceMapper balanceMapper;
    @Autowired
    private ErpCategoryMapper categoryMapper;
    @GetMapping("/print-list")
    @ApiOperation("打印列表")
    public Result goodsList(Integer[] ids) {
        JSONArray array = erpGoodService.printList(ids);
        if (array.isEmpty()) {
            return ResultUtil.error("没有数据");
        } else {
            return ResultUtil.success("成功", array);
        }
    }

    @PostMapping("/add")
    @ApiOperation("添加商品")
    public Result addGoods(@ApiParam("商品") ErpGoods goods) {

        if (goods.getDiscount() > 1.0 || goods.getDiscount() < 0) {
            return ResultUtil.error("商品折扣错误!");
        }

        if (erpGoodService.addErpGood(goods)) {
            return ResultUtil.success("成功!", goods);
        }
        return ResultUtil.error("添加失败!");
    }

    @PostMapping("/update")
    @ApiOperation("根据ID更新商品")
    public Result updateGoodsById(@ApiParam("商品") ErpGoods goods) {
        if (goods.getGoodsId() <= 0) {
            return ResultUtil.error("商品ID异常.");
        }

        if (goods.getDiscount() > 1.0 || goods.getDiscount() < 0) {
            return ResultUtil.error("商品折扣错误!");
        }

        if (erpGoodService.updateErpGood(goods)) {
            return ResultUtil.success("更新成功!");
        }
        return ResultUtil.error("更新失败!");
    }

    @GetMapping("/{id}")
    @ApiOperation("查询商品")
    public Result getGoods(@ApiParam("商品ID") @PathVariable int id) {
        if (id < 0) {
            return ResultUtil.error("错误的商品ID!");
        }
        ErpGoods good = erpGoodService.selectById(id);

        if (good == null) {
            return ResultUtil.error("没有发现商品!");
        }
        return ResultUtil.success("成功!", good);
    }

    @GetMapping("/sn/{goodsSn}")
    @ApiOperation("查询商品根据SN")
    public Result getGoodsBySn(@ApiParam("goodsSn") @PathVariable String goodsSn) {
        if (Strings.isNullOrEmpty(goodsSn)) {
            return ResultUtil.error("错误的商品编号!");
        }
        ErpGoods good = erpGoodService.selectBySn(goodsSn);
        if (good == null) {
            return ResultUtil.error("没有发现对应商品");
        }
        return ResultUtil.success("成功!", good);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除商品")
    public Result delete(@ApiParam("商品ID") @PathVariable int id) {
        if (id < 0) {
            return ResultUtil.error("错误的商品ID!");
        }
        List<Integer> list = Arrays.asList(id);
        if (erpGoodService.deleteErpGood(list)) {
            return ResultUtil.success("删除成功!");
        } else {
            return ResultUtil.error("删除失败!");
        }
    }

    @GetMapping("/delete/some")
    @ApiOperation("删除一堆商品")
    public Result delete(@ApiParam("商品ID集合") @RequestParam("ids") Integer[] array) {
        List<Integer> list = Arrays.asList(array);
        if (list.isEmpty()) {
            return ResultUtil.error("商品ID异常!");
        }
        if (erpGoodService.deleteErpGood(list)) {
            return ResultUtil.success("删除成功!");
        } else {
            return ResultUtil.error("删除失败!");
        }
    }

    @GetMapping("/code-list/{current}/{size}/{cate}/{sup}/{code}/{sale}/{status}")
    @ApiOperation("查询商品根据自定码")
    @ResponseBody
    public Result listByCode(
            @ApiParam("查询条件") @RequestParam("search") String search,
            @ApiParam("分类ID") @PathVariable int cate,
            @ApiParam("供应商ID") @PathVariable int sup,
            @ApiParam("查询数量") @PathVariable int size,
            @ApiParam("查询页数") @PathVariable int current,
            @ApiParam("商品是否自定义条码") @PathVariable int code,
            @ApiParam("商品是否促销") @PathVariable int sale,
            @ApiParam("状态") @PathVariable int status) {
        if (current < 1) {
            return ResultUtil.error("查看页数无效!");
        }
        if (size < 1) {
            return ResultUtil.error("每页查询数量无效!");
        }
        IPage<ErpGoods> goods = erpGoodService.erpGoodsList(search, current, size, cate, sup, code, sale, status);
        return ResultUtil.success("成功!", goods);
    }

    /**
     * 商品查询根据 编号,规格型号,名称,
     *
     * @return
     */
    @GetMapping("/list/{current}/{size}/{cate}/{sup}/{status}")
    @ApiOperation("查询商品")
    public Result list(
            @ApiParam("查询条件") @RequestParam("search") String search,
            @ApiParam("分类ID") @PathVariable int cate,
            @ApiParam("供应商ID") @PathVariable int sup,
            @ApiParam("查询数量") @PathVariable int size,
            @ApiParam("查询页数") @PathVariable int current,
            @ApiParam("状态") @PathVariable int status) {
        if (current < 1) {
            return ResultUtil.error("查看页数无效!");
        }

        if (size < 1) {
            return ResultUtil.error("每页查询数量无效!");
        }

        IPage<ErpGoods> goods = erpGoodService.erpGoodsList(search, current, size, cate, sup, status);
        return ResultUtil.success("成功!", goods);
    }

    @GetMapping("/warehouse-list/sn/{goodsSn}")
    @ApiOperation("查询仓库里的商品,更具商品编号")
    public Result listOfWarehouse(@ApiParam("商品编号") @PathVariable String goodsSn) {
        if (Strings.isNullOrEmpty(goodsSn)) {
            return ResultUtil.error("商品号错误");
        }
        ErpGoods goods = erpGoodService.erpGoodsOfWarehouseBySn(goodsSn);
        if (goods == null) {
            return ResultUtil.error("没有发现对应商品");
        }
        return ResultUtil.success("成功", goods);
    }

    /**
     * 商品查询根据 编号,规格型号,名称
     *
     * @return
     */
    @GetMapping("/warehouse-list/{current}/{size}")
    @ApiOperation("查询仓库里的商品")
    public Result listOfWarehouse(
            @ApiParam("查询条件") @RequestParam("search") String search,
            @ApiParam("查询数量") @PathVariable int size,
            @ApiParam("查询页数") @PathVariable int current) {
        if (current < 1) {
            return ResultUtil.error("查看页数无效!");
        }
        if (size < 1) {
            return ResultUtil.error("每页查询数量无效!");
        }
        IPage<ErpGoods> goods = erpGoodService.erpGoodsListOfWarehouse(search, current, size);
        return ResultUtil.success("成功!", goods);
    }

    @GetMapping("/unit")
    @ApiOperation("获取所有的小单位")
    public Result smallUntis() {
        return ResultUtil.success("成功!", smallUnitMapper.selectList(null));
    }

    @GetMapping("/brands")
    @ApiOperation("获取所有的品牌列表")
    public Result brands() {
        return ResultUtil.success("成功!", brandMapper.selectList(null));
    }

    @GetMapping("/supplier-list/{id}")
    @ApiOperation("供应商的商品列表")
    public Result listOfTheSuppliers(@ApiParam("供应商的ID") @PathVariable int id) {
        List<ErpTempOrderItem> orders = erpGoodService.listOfSupplier(id);
        if (orders != null) {
            return ResultUtil.success("成功!", orders);
        }
        return ResultUtil.error("失败,无数据!");
    }

    /**
     * 采购列表
     *
     * @param start
     * @param end
     * @param search
     * @return
     */
    @GetMapping("/store-list")
    @ApiOperation("查询订单列表列出门店订单商品,根据时间及条件信息查询订单条件")
    public Result listOfStore(
            @ApiParam("开始时间") @RequestParam("start") String start,
            @ApiParam("结束时间") @RequestParam("end") String end,
            @ApiParam("查询条件") @RequestParam("search") String search) {
        List<FactoryOrder> orders = erpGoodService.listOfStore(start, end, search);
        if (orders == null) {
            return ResultUtil.error("没有数据抱歉!");
        }
        return ResultUtil.success("成功!", orders);
    }

    @GetMapping("/confirm-store-list")
    @ApiOperation("查询订单列表列出门店订单商品,根据时间及条件信息查询订单条件,confirm为1")
    public Result listOfStoreAndConfirm(
            @ApiParam("开始时间") @RequestParam("start") String start,
            @ApiParam("结束时间") @RequestParam("end") String end,
            @ApiParam("查询条件") @RequestParam("search") String search) {
        List<FactoryOrder> orders = erpGoodService.listOfStoreAndConfirm(start, end, search);
        if (orders == null) {
            return ResultUtil.error("没有数据抱歉!");
        }
        return ResultUtil.success("成功!", orders);
    }

    @GetMapping("/store-list-stockout")
    @ApiOperation("查询订单列表列出门店订单缺货的商品")
    public Result listOfStoreStockOut() {
        List<ErpGoods> goods = erpGoodService.stockOutGoods();
        if (goods != null) {
            return ResultUtil.success("成功!", goods);
        } else {
            return ResultUtil.result(300, "没有紧急库存商品", null);
        }
    }

    @PostMapping("/replenish-goods/{id}/{num}")
    @ApiOperation("补出货")
    public Result replenishGoods(@ApiParam("ID") @PathVariable int id, @ApiParam("补出货数量") @PathVariable int num) {

        if (id < 0 || num < 0) {
            return ResultUtil.error("错误的参数!");
        }
        try {
            if (erpGoodService.replenishGoods(id, num)) {
                return ResultUtil.success("成功");
            } else {
                return ResultUtil.error("失败");
            }
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/bought/{catId}/{brandId}/{supplierId}/{current}/{size}/{type}/{mode}")
    @ApiOperation("我要采购接口")
    public Result iWantToBuy(@ApiParam("分类ID") @PathVariable int catId,
                             @ApiParam("品牌ID") @PathVariable int brandId,
                             @ApiParam("页面") @PathVariable int current,
                             @ApiParam("项数") @PathVariable int size,
                             @ApiParam("供应商ID") @PathVariable int supplierId,
                             @ApiParam("排序 0:默认排序, 1:价格排序") @PathVariable int type,
                             @ApiParam("模式 0:普通模式, 1:预警商品") @PathVariable int mode,
                             @ApiParam("名称") @RequestParam("name") String name) {
        IPage<ErpGoods> page = erpGoodService.boughtPage(catId, brandId, supplierId, current, size, type, mode, name);
        return ResultUtil.success("成功!", page);
    }

    @PostMapping("/add-cart")
    @ApiOperation("添加商品到购物车")
    public Result addGoodsToShoppingCart(@ApiParam("用户ID") @RequestParam("userId") int userId,
                                         @ApiParam("商品ID") @RequestParam("goodsId") int goodsId,
                                         @ApiParam("商品数量") @RequestParam("num") int goodsNum) {
        AdminUser user = adminUserMapper.selectById(userId);
        if (user == null) {
            return ResultUtil.error("没有此用户！");
        }
        ErpGoods goods = goodMapper.selectById(goodsId);
        if (goods == null) {
            return ResultUtil.error("没有发现该商品！");
        }
        if (goods.getStatus() != 0) {
            return ResultUtil.error("该商品被禁用! ");
        }
        CartItem item = cartItemMapper.selectCartItemByUserIdAndGoodsId(userId, goodsId);
        if (item != null) {
            item.setGoodsNum(item.getGoodsNum() + goodsNum);
            cartItemMapper.updateById(item);
        } else {
            item = new CartItem();
            item.setGoodsId(goodsId);
            item.setGoodsNum(goodsNum);
            item.setUserId(userId);
            item.setGoodsName(goods.getGoodsName());
            item.setGoodsDesc(goods.getGoodsDesc());
            item.setGoodsThumb(goods.getGoodsThumb());
            item.setBrandName(brandMapper.selectBrandNameByGoodsId(goodsId));
            item.setMarketPrice(goods.getMarketPrice());
            item.setShopPrice(goods.getShopPrice());
            item.setGoodsSn(goods.getGoodsSn());
            item.setSupplierName(supplierMapper.selectSupplierNameByGoodsId(goodsId));
            item.setMinimumQuantity(goods.getMinimumQuantity());
            item.setCreateTime(Instant.now().toEpochMilli() / 1000);
            cartItemMapper.insert(item);
        }
        return ResultUtil.success("成功!");
    }

    @GetMapping("/cart-list/{userId}")
    @ApiOperation("购物车列表")
    public Result shoppingCartList(@ApiParam("用户ID") @PathVariable int userId) {
        List<CartItem> cartItems = cartItemMapper.selectCartItemByUserId(userId);
        Set<String> setNames = new HashSet<>();
        cartItems.forEach(x -> {
            setNames.add(x.getSupplierName());
        });
        JSONArray array = new JSONArray();
        for (String name : setNames) {
            JSONObject object = new JSONObject();
            object.put("name", name);
            object.put("item", cartItems.stream().filter(x -> {
                return x.getSupplierName().equalsIgnoreCase(name);
            }).collect(Collectors.toList()));
            array.add(object);
        }
        return ResultUtil.success("成功", array);
    }

    @GetMapping("/delete-cart")
    @ApiOperation("删除购物车里的商品")
    public Result deleteGoodsToShoppingCart(@ApiParam("商品ID集合") @RequestParam("id[]") Integer[] array) {
        List<Integer> list = Arrays.asList(array);
        if (list.isEmpty()) {
            return ResultUtil.error("没有选择的商品");
        }
        cartItemMapper.deleteBatchIds(list);
        return ResultUtil.success("删除成功!");
    }

    @GetMapping("/out-goods/{goodsId}")
    @ApiOperation("查看出库商品")
    public Result outGoods(@PathVariable int goodsId) {
        JSONObject list = erpGoodService.outGoods(goodsId);
        if (list.size() > 0) {
            return ResultUtil.success("成功", list);
        } else {
            return ResultUtil.error("查询成功");
        }
    }

    @GetMapping("/all-goods/{goodsId}")
    @ApiOperation("查看入库商品")
    public Result inGoods(@PathVariable int goodsId) {
        List<ErpOrderItem> list = erpGoodService.inGoods(goodsId);
        if (list.size() > 0) {
            return ResultUtil.success("成功", list);
        } else {
            return ResultUtil.error("该商品没有库存操作!");
        }

    }


    @GetMapping("/i")
    @ApiOperation("查看入库商品")
    public Result i() {
        QueryWrapper<ErpGoods> w = new QueryWrapper<>();
        List<ErpGoods> list = goodMapper.selectList(w);
        int rs=0;
        for (ErpGoods erpGoods:list){
            ErpWarehouseItem erpWarehouseItem  = goodMapper.getGoodsWhId(erpGoods.getGoodsId());
            if (erpWarehouseItem!=null){
                erpGoods.setWhId(erpWarehouseItem.getWhId());
                rs +=goodMapper.updateById(erpGoods);
            }

        }

       return  ResultUtil.success("1",rs);
    }

    @GetMapping(value="/export",produces = {"application/vnd.ms-excel;charset=UTF-8"})
    @ApiOperation("导出未入库订单信息")
    public String export(HttpServletResponse response) throws IOException {
        return erpGoodService.export(response);
    }
}
